<template>
  <view class="order-container">
    <!-- 内容滚动区域 -->
    <scroll-view scroll-y class="content-area" @scrolltolower="loadMore" :scroll-top="scrollTop">
      <!-- 顶部 tabs：全部订单 / 已完成订单 -->
      <view class="tabs-top">
        <view :class="['tab-top-item', { active: activeTop === 'all' }]" @click="switchTop('all')">全部订单</view>
        <view :class="['tab-top-item', { active: activeTop === 'completed' }]" @click="switchTop('completed')">已完成订单
        </view>
      </view>

      <!-- 二级 tabs（仅在全部订单显示）：待接单/进行中/待付款 -->
      <view v-if="activeTop === 'all'" class="tabs-sub">
        <view :class="['tab-sub-item', { active: activeSub === 'pending' }]" @click="switchSub('pending')">待接单</view>
        <view :class="['tab-sub-item', { active: activeSub === 'delivery' }]" @click="switchSub('delivery')">进行中</view>
        <view :class="['tab-sub-item', { active: activeSub === 'pendingpay' }]" @click="switchSub('pendingpay')">待付款
        </view>
      </view>

      <!-- 订单列表 -->
      <view class="card-list">
        <view v-for="(item, idx) in computedList" :key="idx" class="order-card">
          <view class="card-main">
            <!-- 左侧图标块 -->
            <view class="oil-block">

              <image :src="item.goods_image" mode="aspectFill" style="width: 100%; height: 100%;" />
            </view>

            <!-- 右侧信息 -->
            <view class="info-block" @click="gotoDetail(item)">
              <view class="header-row">
                <text class="title">{{ item.goods_name }}</text>
                <text class="status-text">{{ item.statusText }}</text>
              </view>
              <view class="meta-row">
                <text class="label">用油量：</text>
                <text class="value">{{ item.usage }}升</text>
              </view>
              <view class="meta-row">
                <text class="label">下单时间：</text>
                <text class="value">{{ formatDateTime(item.order_time) }}</text>
              </view>
              <view class="meta-row">
                <text class="label">用油时间：</text>
                <text class="value">{{ formatDateTime(item.use_time) }}</text>
              </view>
            </view>
          </view>

          <!-- 状态按钮：进行中->取消订单；待付款->去付款；其他状态->无按钮 -->
          <view v-if="item.action" class="action-row">
            <uv-button :text="item.action" size="large" :custom-style="primaryBtn" @click="onAction(item)" />
          </view>
        </view>

        <!-- 加载状态 -->
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 空状态 -->
        <view v-if="!loading && computedList.length === 0" class="empty-container">
          <uv-empty text="暂无订单数据" />
        </view>

        <!-- 没有更多数据 -->
        <view v-if="!loading && !hasMore && computedList.length > 0" class="no-more-container">
          <text class="no-more-text">没有更多数据了</text>
        </view>
      </view>
    </scroll-view>

    <!-- 固定在底部的TabBar -->
    <view class="tabbar-container">
      <UserTabBar />
    </view>

    <!-- 取消原因弹窗 -->
    <CancelReasonModal ref="cancelModalRef" @close="closeCancelModal" @submit="handleCancelSubmit" />
  </view>
</template>

<script setup lang="ts">
import { ref, onUnmounted, onMounted } from 'vue'
import { formatDateTime } from '@/utils/dateTime'
import { useRequest } from '@/api'
const { API_ORDER_LIST, API_CANCEL_ORDER } = useRequest()
import UserTabBar from '@/components/tabbar/UserTabBar.vue'
import CancelReasonModal from './CancelReasonModal.vue'
import { UserInfoManager } from '@/utils/userInfo'

const activeTop = ref<'all' | 'completed'>('all')
const activeSub = ref<'pending' | 'delivery' | 'pendingpay'>('pending')

const computedList = ref([])
const loading = ref(false)
const hasMore = ref(true)
const total = ref(0)
const scrollTop = ref(0)

// 取消原因弹窗引用
const cancelModalRef = ref()
const currentOrderId = ref<number | null>(null)

const switchTop = (val: 'all' | 'completed') => {
  activeTop.value = val
  resetPagination()
  getList1()
}

const switchSub = (val: 'pending' | 'delivery' | 'pendingpay') => {
  activeSub.value = val
  resetPagination()
  getList1()
}

const primaryBtn = {
  width: '100%',
  height: '88rpx',
  borderRadius: '12rpx',
  backgroundColor: '#FF6B35',
  color: '#fff',
  fontSize: '30rpx',
  fontWeight: '600'
}

const onAction = async (item: any) => {
  if (item.status === 'delivery') {
    // 进行中的订单可以取消
    currentOrderId.value = item.id
    cancelModalRef.value?.open()
  } else if (item.status === 'pendingpay') {
    if (item.order_type == 'balance') {
      uni.navigateTo({ url: '/user/order/detailPay1?id=' + item.id })
    } else {
      uni.navigateTo({ url: '/user/order/detailPay2?id=' + item.id })
    }
  }
}

const gotoDetail = (item: any) => {
  if (item.status === 'pending') {
    uni.navigateTo({ url: '/user/order/detail1?id=' + item.id })
  } else if (item.status === 'delivery') {
    uni.navigateTo({ url: '/user/order/detail2?id=' + item.id })
  } else if (item.status === 'pendingpay') {
    uni.navigateTo({ url: '/user/order/detail3?id=' + item.id })
  } else {
    uni.navigateTo({ url: '/user/order/detail4?id=' + item.id })
  }

}

const page = ref(1)
const pageSize = 10

const getList1 = async (isLoadMore = false) => {
  if (loading.value) return

  loading.value = true

  // 根据不同的tab选择设置对应的status
  let status = ''
  if (activeTop.value === 'completed') {
    status = 'completed'
  } else {
    // 全部订单下的子tab
    if (activeSub.value === 'pending') {
      status = 'pending'
    } else if (activeSub.value === 'delivery') {
      status = 'delivery'
    } else if (activeSub.value === 'pendingpay') {
      status = 'pendingpay'
    }
  }

  const params = {
    status: status,
    isdriver: UserInfoManager.lastrole(),
    page: page.value,
    page_size: pageSize
  }

  try {
    const res = await API_ORDER_LIST(params)
    if (res.code === 1) {
      const newData = res.data.data || []
      total.value = res.data.total || 0


      newData.forEach((item) => {

        if (item.status === 'pending') {
          item.action = ''
          item.statusText = '待接单'
        } else if (item.status === 'delivery') {
          item.action = '取消订单'
          item.statusText = '进行中'
        } else if (item.status === 'pendingpay') {
          item.action = '去付款'
          item.statusText = '待付款'
        } else if (item.status === 'completed') {
          item.action = ''
          item.statusText = '已完成'
        }
      })

      if (isLoadMore) {
        // 上拉加载更多，追加数据
        computedList.value = [...computedList.value, ...newData]
      } else {
        // 首次加载或切换tab，替换数据
        computedList.value = newData
      }

      // 判断是否还有更多数据
      hasMore.value = computedList.value.length < total.value

    }
  } catch (error) {

  } finally {
    loading.value = false
  }
}

// 重置分页
const resetPagination = () => {
  page.value = 1
  hasMore.value = true
  computedList.value = []
}

// 加载更多
const loadMore = async () => {
  if (loading.value || !hasMore.value) return

  page.value++
  await getList1(true)
}



// 关闭取消原因弹窗
const closeCancelModal = () => {
  cancelModalRef.value?.close()
  currentOrderId.value = null
}

// 处理取消原因提交
const handleCancelSubmit = async (reason: string) => {

  try {
    const params = {
      id: currentOrderId.value,
      reason: reason,
      isdriver: UserInfoManager.lastrole()
    }
    const res = await API_CANCEL_ORDER(params)

    if (res.code === 1) {
      uni.showToast({
        title: '订单已取消',
        icon: 'success'
      })
    }
  } catch (error) {

  } finally {
    closeCancelModal()
    resetPagination()
    getList1()
  }
}

onMounted(() => {
  getList1()
  uni.$on('refOrderList', () => {
    setTimeout(() => {
      resetPagination()
      getList1()
    }, 200)
  })
})

onUnmounted(() => {
  uni.$off('refOrderList')
})
</script>

<style lang="scss" scoped>
.order-container {
  min-height: 100vh;
  background: #f6f7f9;
  display: flex;
  flex-direction: column;
}

.content-area {
  flex: 1;
  padding: 20rpx 0;
  padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.tabs-top {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 0 24rpx;
}

.tab-top-item {
  font-size: 34rpx;
  color: #8c8c8c;
  padding: 16rpx 8rpx;
  position: relative;
}

.tab-top-item.active {
  color: #1f1f1f;
  font-weight: 700;
}

.tabs-sub {
  display: flex;
  gap: 16rpx;
  padding: 0 24rpx;
  margin-bottom: 12rpx;
}

.tab-sub-item {
  padding: 12rpx 24rpx;
  border-radius: 26rpx;
  background: #f5f5f5;
  color: #666;
  font-size: 26rpx;
}

.tab-sub-item.active {
  background: #fff0e6;
  color: #ff6b35;
  border: 1rpx solid #ff6b35;
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  padding: 0 24rpx;
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
  padding: 24rpx;
}

.card-main {
  display: flex;
  gap: 20rpx;
}

.oil-block {
  width: 180rpx;
  height: 180rpx;
  border-radius: 16rpx;
  background: #fff5f0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.oil-tag {
  margin-top: 8rpx;
  font-size: 48rpx;
  font-weight: 800;
  color: #1f1f1f;
}

.info-block {
  flex: 1;
}

.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.title {
  font-size: 34rpx;
  font-weight: 700;
  color: #1f1f1f;
}

.status-text {
  font-size: 30rpx;
  color: #8c8c8c;
}

.meta-row {
  margin: 10rpx 0;
}

.label {
  font-size: 28rpx;
  color: #8c8c8c;
}

.value {
  font-size: 28rpx;
  color: #1f1f1f;
}

.action-row {
  margin-top: 20rpx;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.empty-container {
  padding: 80rpx 0;
}

.no-more-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.no-more-text {
  font-size: 26rpx;
  color: #999;
}

.tabbar-container {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}
</style>
